<template>
  <div class="box">
    <van-nav-bar
      title="用户登录"
      left-text="返回"
      right-text="注册"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push('/reg')"
    />
    <div class="login">
      <h1>用户登录</h1>
      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />

        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >登录</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  created() {
    //接收注册时跳转到本页面的用户名
    const { username } = this.$route.query;
    this.username = username;
  },
  methods: {
    async onSubmit(values) {
      const data = await this.$store.dispatch("user/login", values);
      //登录成功与登录失败
      if (data.status === 0) {
        this.$notify({ type: "danger", message: "用户名或密码错误" });
      } else if (data.status === 200) {
        //登录成功默认跳转我的页面 或者购物车页面
        const { targetUrl = "/mine" } = this.$route.query;
        this.$router.replace(targetUrl);
      }
    },
  },
};
</script>
<style scoped>
.box {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 50px);
}
.login {
  height: 100%;
  width: 100%;
  background-image: url("https://iconfont.alicdn.com/t/83c9b687-a91e-47ce-be67-ec20dd1bf40c.png");
  background-repeat: no-repeat;
  background-size: cover;
  overflow: hidden;
  flex: 1;
}
.van-form {
  width: 80%;
  height: 40%;
  margin: 120px auto;
  background-color: #fff;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 3px 8px 0 rgba(0, 0, 0, 0.19);
}
.van-button {
  margin-bottom: 10px;
}
</style>